package com.arcsoft.crud.limitTime.base;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

import com.arcsoft.crud.Constants.Global;
import com.arcsoft.crud.base.TaskBase;
import com.arcsoft.crud.util.ConnectionDB;

public abstract class BenchmarkTimeTask extends TaskBase {

	CountDownLatch finishLatch;
	public BenchmarkTimeTask(int threadIndex, CountDownLatch parent, int printInfoInterval, String taskLogTable) {
		super (printInfoInterval, taskLogTable, threadIndex);
		this.finishLatch = parent;
	}

	@Override
	public void run() {
		System.out.println("thread"+threadIndex +" is start");
		Date startDate = new Date();
		long i=0;
		float excuteTime = (Global.EXECUTE_TIME+((float)Global.WARMTIME/Global.THREAD_COUNT)*(Global.THREAD_COUNT-threadIndex))*1000;
		
		try{
			while(true){
				i++;
				if(new Date().getTime() - startDate.getTime() >= excuteTime){//第一个线程要比最后一个线程多执行执行时间-一个线程执行所需要时间
					break;
				}
				String requestDetail = execute();
				Date endDate = new Date();
				this.printInfo(i,startDate);
				logInfo(startDate, endDate,requestDetail,new Long(endDate.getTime()-startDate.getTime()).intValue());
			}
		}catch(Exception e){
			logInfo(startDate, new Date(), e.toString(), 0);
		}finally{
			onThreadFinish();
		}
		double tps = i*1000/(System.currentTimeMillis()-startDate.getTime());
		System.out.println("thread"+threadIndex+" spend: "+(System.currentTimeMillis()-startDate.getTime())/1000+" s for "+i+" requests, TPS is "+tps);
	}
	
	protected void onThreadFinish() {
		finishLatch.countDown();
	}
	
	public abstract String execute();
	
}